package com.swotplus.admin.web.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swotplus.framework.web.BaseController;
import com.swotplus.common.annotation.Log;
import com.swotplus.common.constant.UserConstants;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.common.enums.BusinessType;
import com.swotplus.common.utils.Convert;
import com.swotplus.common.utils.StringUtils;
import com.swotplus.framework.shiro.ShiroUtils;
import com.swotplus.system.sys.entity.SysRole;
import com.swotplus.system.sys.entity.SysUser;
import com.swotplus.system.sys.service.SysRoleService;
import com.swotplus.system.sys.service.SysUserService;
import com.swotplus.system.sys.vo.SysRoleVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    private String prefix = "system/role";

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserService sysUserService;

    @RequiresPermissions("system:role:view")
    @GetMapping()
    public String role()
    {
        return prefix + "/list";
    }

    @RequiresPermissions("system:role:list")
    @RequestMapping("/list")
    @ResponseBody
    public AjaxResult list(SysRoleVo vo)
    {
        Page<SysRole> page=new Page<>(vo.getPage(),vo.getLimit());
        QueryWrapper<SysRole> sysRoleQueryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(vo.getRoleName())){
            sysRoleQueryWrapper.eq("role_name",vo.getRoleName());
        }
        if(StringUtils.isNotBlank(vo.getDataScope())){
            sysRoleQueryWrapper.eq("data_scope",vo.getDataScope());
        }
        IPage<SysRole> pageList= sysRoleService.page(page,sysRoleQueryWrapper);
        return AjaxResult.success("成功", (int) pageList.getTotal(),pageList.getRecords());
    }


    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysRole role,String... menuIds)
    {
        QueryWrapper<SysRole> queryNameWrapper=new QueryWrapper<>();
        queryNameWrapper.eq("role_name",role.getRoleName());

        QueryWrapper<SysRole> queryKeyWrapper=new QueryWrapper<>();
        queryKeyWrapper.eq("role_key",role.getRoleKey());

        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(sysRoleService.count(queryNameWrapper)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(sysRoleService.count(queryKeyWrapper)))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysRoleService.saveRoleMenu(role,menuIds));

    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{roleId}")
    public String edit(@PathVariable("roleId") String roleId, ModelMap mmap)
    {
        mmap.put("role", sysRoleService.getById(roleId));
        return prefix + "/edit";
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysRole role,String... menuIds)
    {
        QueryWrapper<SysRole> queryNameWrapper=new QueryWrapper<>();
        queryNameWrapper.eq("role_name",role.getRoleName());

        QueryWrapper<SysRole> queryKeyWrapper=new QueryWrapper<>();
        queryKeyWrapper.eq("role_key",role.getRoleKey());
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(sysRoleService.count(queryNameWrapper)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(sysRoleService.count(queryKeyWrapper)))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysRoleService.updateRoleMenu(role,menuIds));
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{roleId}")
    public String authDataScope(@PathVariable("roleId") String roleId, ModelMap mmap)
    {
        mmap.put("role", sysRoleService.getById(roleId));
        return prefix + "/dataScope";
    }

//    /**
//     * 保存角色分配数据权限
//     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
//    @PostMapping("/authDataScope")
//    @ResponseBody
//    public AjaxResult authDataScopeSave(SysRole role)
//    {
//        role.setUpdateBy(ShiroUtils.getLoginName());
//        if (sysRoleService.authDataScope(role) > 0)
//        {
//            ShiroUtils.setSysUser(sysUserService.getById(ShiroUtils.getSysUser().getId()));
//            return success();
//        }
//        return error();
//    }

    @RequiresPermissions("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            List<String> listIds=new ArrayList<>();
            String[] s= Convert.toStrArray(ids);
            for (String i:s){
                listIds.add(i);
            }
            return toAjax(sysRoleService.removeByIds(listIds));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(SysRole role)
    {
        QueryWrapper<SysRole> queryNameWrapper=new QueryWrapper<>();
        queryNameWrapper.eq("role_name",role.getRoleName());
        if(sysRoleService.count(queryNameWrapper)>0){
            return UserConstants.ROLE_NAME_NOT_UNIQUE;
        }

        return UserConstants.ROLE_NAME_UNIQUE;
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkRoleKeyUnique")
    @ResponseBody
    public String checkRoleKeyUnique(SysRole role)
    {

        QueryWrapper<SysRole> queryKeyWrapper=new QueryWrapper<>();
        queryKeyWrapper.eq("role_key",role.getRoleName());
        if(sysRoleService.count(queryKeyWrapper)>0){
            return UserConstants.ROLE_KEY_NOT_UNIQUE;
        }

        return UserConstants.ROLE_KEY_UNIQUE;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree")
    public String selectMenuTree()
    {
        return prefix + "/tree";
    }

    /**
     * 角色状态修改
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:role:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysRole role)
    {
//        sysRoleService.checkRoleAllowed(role);
        return toAjax(sysRoleService.updateById(role));
    }

    /**
     * 分配用户
     */
    @RequiresPermissions("system:role:edit")
    @GetMapping("/authUser/{roleId}")
    public String authUser(@PathVariable("roleId") String roleId, ModelMap mmap)
    {
        mmap.put("role", sysRoleService.getById(roleId));
        return prefix + "/authUser";
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/allocatedList")
    @ResponseBody
    public AjaxResult allocatedList(SysUser user)
    {
        return AjaxResult.success();
    }

//    /**
//     * 取消授权
//     */
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @PostMapping("/authUser/cancel")
//    @ResponseBody
//    public AjaxResult cancelAuthUser(SysUserRole userRole)
//    {
//        return toAjax(sysRoleService.deleteAuthUser(userRole));
//    }

//    /**
//     * 批量取消授权
//     */
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @PostMapping("/authUser/cancelAll")
//    @ResponseBody
//    public AjaxResult cancelAuthUserAll(Long roleId, String userIds)
//    {
//        return toAjax(sysRoleService.deleteAuthUsers(roleId, userIds));
//    }

    /**
     * 选择用户
     */
    @GetMapping("/authUser/selectUser/{roleId}")
    public String selectUser(@PathVariable("roleId") String roleId, ModelMap mmap)
    {
        mmap.put("role", sysRoleService.getById(roleId));
        return prefix + "/selectUser";
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/unallocatedList")
    @ResponseBody
    public AjaxResult unallocatedList(SysUser user)
    {
        return AjaxResult.success();
    }

//    /**
//     * 批量选择用户授权
//     */
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @PostMapping("/authUser/selectAll")
//    @ResponseBody
//    public AjaxResult selectAuthUserAll(String roleId, String userIds)
//    {
//
//        return toAjax(sysRoleService.save(roleId, userIds));
//    }
}